const xss = require('xss');
const { exec, escape } = require('../db/mysql');
const { genPassword } = require('../utils/cryp'); // 加密

const getArticleList = (id, keyWord) => {
    // console.log('author, keyword', author, keyword)
    // let sql = `SELECT * FROM article where 1=1 `; // 写1=1的作用是防止sql语句报错，避免author, keyword都不存在的情况下
    // if (author) {
    //     sql+=`and author='${author}' `;
    // }
    // if (keyword) {
    //     sql+=`and title like '%${keyword}%' `;
    // }
    // sql+= `order by createtime desc;`
    // 返回的是一个promise
    let sql = `SELECT * FROM article where 1=1`
    console.log('exec(sql)', exec(sql))
    return exec(sql);
}

const getArticleDetail = (id) =>{
    let sql = `SELECT * FROM article where id='${id}'`;
    return exec(sql).then(rows => {
        return rows[0]; // 返回的还是一个promise
    });
}

const addArticle = (blogData = {} ) =>{
    const { title, content, author, subtitle } = blogData;
    const createtime = Date.now();
    const sql = `insert into article (title, content, createtime, author, subtitle)
        values ('${title}', '${content}', '${createtime}', '${author}',  '${subtitle}');
    `
    return exec(sql).then(insertData => {
        console.log('insertData is', insertData);
        return {
            id: insertData.insertId, // 插入的主建id
        }
    });
}

// 更新博客
const updateArticle = (blogData ={}) =>{
    const { title, content, author="mashitu", subtitle, id } = blogData;
    const createtime = Date.now();
    console.log('id===>======', blogData)
    let sql = `UPDATE article SET title='${title}',createtime='${createtime}',content='${content}',author='${author}',subtitle='${subtitle}' WHERE id='${id}'`;
    return exec(sql).then(updateData => {
        console.log('updateData, updateData===>', updateData)
        return {
            id: updateData,
        }
    });
}

const deleteArticle = ({ id }) => {
    // id 就是删除blog的id
    let sql = `DELETE from article WHERE id='${id}'`;
    return exec(sql).then(delData => {
        console.log('delData, delData', delData)
        return {
            id: delData
        }
    });
}

module.exports = {
    getArticleList,
    getArticleDetail,
    addArticle,
    updateArticle,
    deleteArticle
};